// JavaScript Document
define(function (require, exports, module) {
	var Page=require("Page");
	var Verifier=require("Verifier");
	var Utils=require("Utils");

	var Form=function(selector){
		Page.call(this)
		if(arguments.length>0){
			this.element=$(selector).get(0);
		}
	}
	Form.prototype=new Page();

	Form.ACTION_CREATE="create"
	Form.ACTION_EDIT="edit"
	Form.prototype.sourceRuleNames=new Array();
	Form.prototype.ruleNames=new Array();


	Form.prototype.formData=Array();
	Form.prototype.formRule=null;
	Form.prototype.fieldsRule=null;
	Form.prototype.formRuleLoaded=false;
	/*Form.prototype.bindFieldsPattern=function(){
		var rule;
		var name
		for(var i in this.rules){
			rule=this.rules[i]
			name=rule.name
			document.getElementsByName(name)[0].setAttribute("required",rule.required)
			document.getElementsByName(name)[0].setAttribute("pattern",rule.pattern)
			document.getElementsByName(name)[0].setAttribute("placeholder",rule.placeholder)
			document.getElementsByName(name)[0].setAttribute("title",rule.title)
		}
	}*/

	Form.prototype.extend=function(obj1,obj2){
		for(var i in obj2){
			obj1[i]=obj2[i];
		}
		return obj1;
	}
	//绑定所有字段规则
	Form.prototype.bindFieldsPattern=function(){
		//对比规则
		if(this.contrastRuleNames(this.sourceRuleNames,this.ruleNames)){
			pConsole.log("rule names agreement");
			pConsole.log(this.ruleNames);
			return false;
		};
		ht.loading.open();

		pConsole.log(this.ruleNames);
		if(this.formRuleLoaded==false){
			return false;
		}
		var ruleName="";
		var rules=Array();

		var formRule=this.formRule;
		var i=0;

		for(i in this.ruleNames){
			ruleName=this.ruleNames[i]
			rules[i]=$.extend({},eval("formRule."+ruleName))
		}

		var total=rules.length
		this.fieldsRule=rules[0]
		for(var i=1;i<total;i++){
			this.fieldsRule=this.extend(this.fieldsRule,rules[i])
		}

		var j=0
		for(var i in this.fieldsRule){
			this.bindFieldPattern(i);
			j++;
			if(j==2){
				//return;
			}
		}
		//重装设置原规则名称
		this.sourceRuleNames=this.ruleNames;

		ht.loading.close();
		return ;
	}
	//绑定字段规则
	Form.prototype.bindFieldPattern=function(key){
		var rule=eval("this.fieldsRule."+key);

		var name="";
		var title="";
		var inputElement=null;
		var requiredStr="";
		var label="";

		name=key
		inputElement=document.getElementsByName(name)[0];

		if(inputElement==null){
			pConsole.log("Waring "+ name +" inputElement is null");
			return false;
		}

		if(rule.required==true || rule.required=="true"){
			requiredStr=Utils.getRequiredStr(inputElement,rule);
			//requiredStr="必需 ";
			label="<span class=\"required\">*</span>"+rule.label
		}else{
			label=rule.label
		}
		var title=rule.label+" "+requiredStr+" "+rule.title



		if(rule.required==true){
			if($(inputElement).is(":visible")){
				inputElement.setAttribute("required","true")
			}
		}else{
			if(title!="inherit"){
				inputElement.removeAttribute("required")
			}
		}

		if(rule.pattern!=""){
			if($(inputElement).is(":visible")){
				inputElement.setAttribute("pattern",rule.pattern)
			}
		}else{
			if(title!="inherit"){
				inputElement.removeAttribute("pattern")
			}
		}
		if(rule.placeholder!="inherit"){
			inputElement.setAttribute("placeholder",rule.placeholder)
		}

		if(title!="inherit" && rule.label!="inherit"){
			inputElement.setAttribute("title",title)
		}

		//tips元素删除与添加
		var lastElement=inputElement.parentNode.lastChild;
		var className=""
		if(typeof(lastElement)!="undefined"){
			if(lastElement.className=="text-muted"){
				$(lastElement).remove();
			};
		}
		var tipsElement=document.createElement("small");
		tipsElement.className="text-muted";
		tipsElement.innerHTML=" "+rule.title;
		//inputElement.parentNode.insertBefore(tipsElement,inputElement.nextSibling);

		inputElement.parentNode.appendChild(tipsElement);

		//更改标题			ps：type！=hidden和name==orgType这个判断条件是新增的	2017 	1	12
		if(rule.label!="inherit"&&($(inputElement).attr("type")!="hidden"||$(inputElement).attr("name")=='orgType')){
			var parentTdElement=Utils.getParentElementByTagName(inputElement,"TD");
			var tagName=parentTdElement.parentNode.children[0].tagName;
			if(tagName=="TH"){
				parentTdElement.parentNode.children[0].innerHTML=label;
			}else{
				pConsole.log(name+"字段结构不正常请检查");
			}

			/*
			var tagName=inputElement.parentNode.parentNode.children[0].tagName;
			if(tagName=="TH"){
				inputElement.parentNode.parentNode.children[0].innerHTML=label;
			}else{
				pConsole.log(name+"字段结构不正常请检查");
			}
			*/
		}



		//失去焦点验证

		$(inputElement).bind("blur",function(event){

			var element=event.currentTarget
			var required=rule.required;
			var pattern=rule.pattern;
			var value=$(element).val()
			var regExp=new RegExp(pattern,"g");
			if(required==true){
				if(value==""){
					$(element).addClass("invalid")
					return true;
				}
			}

			if(value!=""){
				if(!regExp.test(value)){
					$(element).addClass("invalid")
					return true;
				}
			}
			$(element).removeClass("invalid")
			return true;
		})
	}









	Form.prototype.getFrameFormSerialize=function(selector){
		if(typeof($(selector).get(0).contentWindow.getFormSerialize)=="undefined"){
			pConsole.log(selector+" getFormSerialize function no found");
			return "";
		}
		var formSerialize=$(selector).get(0).contentWindow.getFormSerialize();
		return formSerialize
	}
	Form.prototype.getSelectorValue=function(selector){
		if(typeof($(selector).get(0).contentWindow.getSelectedIds)=="undefined"){
			pConsole.log(selector+" getSelectedIds function no found");
			return "";
		}
		var value=$(selector).get(0).contentWindow.getSelectedIds();
		return value
	}

	//获得表单数据 拥有&拆分出错
	/*Form.prototype.getFormData=function(){
		var serialize=$(this.element).serialize();
		serialize=decodeURIComponent(serialize,true);
		//var serialize=$("#form").serialize();
		var serializeList=serialize.split("&");

		var keyValue=Array();
		var data=Array()
		var key;
		var value;

		for(var i=0;i<serializeList.length;i++){
			keyValue=serializeList[i].split("=")
			key=keyValue[0]
			value=keyValue[1]
			data[key]=value
		}
		return data;
	}*/

	Form.prototype.getData=function(){
		return this.getFormData();
	}
	//获得表单数据
	Form.prototype.getFormData=function(){
		var serializeArray=$(this.element).serializeArray();
		var data=Array()
		var key;
		var value;

		for(var i=0;i<serializeArray.length;i++){
			//key=decodeURIComponent(serializeArray[i].name,true);
			//value=decodeURIComponent(serializeArray[i].value,true);

			key=serializeArray[i].name;
			value=serializeArray[i].value;

			data[key]=value;
		}
		return data;
	}
	Form.prototype.getFormDataItemValue=function(name){
		var serializeArray=$(this.element).serializeArray();
		var value="";
		for(var i=0;i<serializeArray.length;i++){
			if(name==serializeArray[i].name){
				value=serializeArray[i].value;
				return value;
			};
		}
		return "";
	}

	Form.prototype.validate=function(){
		this.formData=this.getFormData();
		console.log("this.fieldsRule is :"+this.fieldsRule);
		console.log("this.formData is :"+this.formData);
		console.log("this.element is :"+this.element);
		return Verifier.validate(this.fieldsRule,this.formData,this.element);
	}

	/*
	Form.prototype.validate=function(){
		var success,rule,name,value,element,pattern,required,regExp,tips,validateTips;
		tips="";
		success=true;
		required=false;

		var focusElement=null;
		for(var i in this.rules){
			rule=this.rules[i]
			name=rule.name
			pattern=rule.pattern
			required=rule.required

			element=document.getElementsByName(name)[0]
			value=element.value

			if(required==true && pattern!=""){
				regExp=new RegExp(pattern,"g");
				if(!regExp.test(value)){
					success=false
					tips+=element.title+"\r\n"
					if(focusElement==null){
						focusElement=element
					}
				};
			}
		}
		focusElement.focus()
		if(success==false){
			alert(tips);
		}
		return success;
	}
	*/
















	Form.prototype.resetInputValue=function(){
		var elements=this.element.getElementsByTagName("input")
		for(var i=0;i<elements.length;i++){
			elements[i].value=""
			$(elements[i]).removeClass("invalid").removeClass("valid");
		}
	}
	Form.prototype.resetTextAreaValue=function(){
		var elements=this.element.getElementsByTagName("textarea")
		for(var i=0;i<elements.length;i++){
			elements[i].value=""
			$(elements[i]).removeClass("invalid").removeClass("valid");
		}
	}

	Form.prototype.clearSelectSelected=function(){
		var elements=this.element.getElementsByTagName("select")
		for(var i=0;i<elements.length;i++){
			for (var j = 0; j < elements[i].options.length; j++) {
				$(elements[i].options[j]).removeAttr("selected");
				$(elements[i]).removeClass("invalid").removeClass("valid");
			}
		}
	}

	Form.prototype.updateRuleNames=function(){
	}


	/*
	 * 这个对比有啥作用，bindFieldsPattern方法最后会将sourceRuleNames指向ruleNames的数组
	 *	这样只有第一次调用bindFieldsPattern或者将sourceRuleNames重新指向其他数组才有可能返回false,验证创建才会进行
	 *	/sfsp/WebContent/in/webcontInfo/js/Form.js 里采用sourceRuleNames = Array() 才实现了动态修改验证效果
	 */
	//对比规则名称
	Form.prototype.contrastRuleNames=function(sourceRuleNames,ruleNames){
		var result=true;
		if(this.ruleNames.length==0){
			return false;
		}
		//原规则名与新规则名长度判断
		var total1=sourceRuleNames.length
		var total2=ruleNames.length;
		var total=0;

		if(total1>total2){
			total=total1;
		}else{
			total=total2;
		}
		for(var i=0;i<total;i++){
			if(sourceRuleNames[i]!=ruleNames[i]){
				return false;
			}
		}
		return result;
	}

	Form.prototype.loadRule=function(url,updateRuleNames){
		var self=this;
		var options={}
		options.url=url,
			options.dataType="json",
			options.cache=false,
			options.success=function(data, textStatus, jqXHR){
				self.formRule=data;
				self.formRuleLoaded=true;
				updateRuleNames()
				//self.bindFieldsPattern();
			},
			options.error=function(){
				console.log("表单规则加载失败");
			}
		$.ajax(options);
	}
	Form.prototype.submitHandle=function(event){
		try{
			if(this.validate()!=true){
				return false;
			}
		}catch(e){
			pConsole.log(e);
			return false;
		}
		return true;
	}
	//20170510 添加的方法作用是根据制定name的input。组装成一个object对象
	Form.prototype.assemblyOfSpecifiedObjects=function(arr1,str){
		var arr=new Array;
		var inputEle=false;
		var reObj=new Object();
		if(arguments.length==2){
			arr=arr1;
			inputEle=$("input[name="+str+"]")
		}else if(arguments.length==1){
			arr=arr1;
		}
		for(var i=0;i<arr.length;i++){
			reObj[arr[i]]=$("input[name="+arr[i]+"]").val();
		}
		if(inputEle===false){
			return reObj;
		}else{
			inputEle.val(JSON2.stringify(reObj));
		}
	}
//下面两个方法是验证码倒计时集合代码
	Form.prototype.validateCodeHandle=function(event,target){
		if($(event.target).hasClass("disabled"))return false;
		var self=this;
		var options = {}
		var target=target;
		var ele= event.target
		$(event.target).data("breakWord",false);
		self.validateCodeSuccess({"ele":ele, "time": 60, "str": $(event.target).html()});
		options.url = $(event.target).attr("href");
		options.dataType = "json";
		var obj={}
		obj[$(target).attr("id")]=$(target).val();
		options.data=obj;
		options.cache = false;
		options.success = function (data, textStatus, jqXHR) {
			if(data.vo.code!=200){
				alert(data.vo.msg);
				$(ele).data("breakWord",true);
			}
		};
		options.error = function (err) {
			console.log(err);
			alert("链接失败，请稍后再试！或者联系管理员");
			$(ele).data("breakWord",true);
		};
		$.ajax(options);

	}
	Form.prototype.validateCodeSuccess = function (obj) {
		var self = this;
		var ele = obj.ele;
		var time = obj.time;
		var str = obj.str;
		var breakWord=$(ele).data("breakWord");
		if(breakWord==true){
			$(ele).html(str).removeClass("disabled");
			return ;
		}
		$(ele).html(time + "秒后可用").addClass("disabled");
		window.setTimeout(function () {
			if (time - 1 > 0) {
				self.validateCodeSuccess({"ele": ele, "time": time - 1, "str": str})
			} else {
				$(ele).html(str).removeClass("disabled");
			}
		}, 1000)
	}
	module.exports = Form;
});